﻿using System.Collections.Generic;
using System.Data;
using Sok.Munkae.Core;
using Sok.Munkae.Core.DataInterfaces;
using Sok.Munkae.Tenant;

namespace Sok.Munkae.Data
{
    public class ProjectRepository : IProjectRepository
    {
        private int organizationId;
        private IDao<Project> repoHelper;
        private ITenantIdentifier tenantIdentifier;

        public ProjectRepository(ITenantIdentifier tenantIdentifier, IDao<Project> dao)
        {
            repoHelper = dao;
            this.tenantIdentifier = tenantIdentifier;
        }

        #region IProjectRepository Members

        public Project Get(int id)
        {
            return
                repoHelper.GetOne(
                    "select Id,[Name] FROM Project WHERE Id = @Id AND OrganizationId = @OrganizationId",
                    new Dictionary<string, object>() {{"@Id", id}, {"@OrganizationId", tenantIdentifier.GetTenantId()}},
                    BuildOne);
        }

        public IList<Project> GetAll()
        {
            return
                repoHelper.GetList(
                    "select Id,[Name] FROM Project WHERE OrganizationId = @OrganizationId",
                    new Dictionary<string, object>() {{"@OrganizationId", tenantIdentifier.GetTenantId()}},
                    BuildList);
        }

        #endregion

        //DEMO CODE QUALITY ALERT! Having this method in each repository is probably to repetitive, consider refactoring (DRY = "Don't Repeat Yourself")
        protected Project BuildOne(IDataReader reader)
        {
            Project project = null;
            if (reader.Read())
            {
                project.Id = (int) reader["Id"];
                project.Name = (string) reader["Name"];

                if (reader.Read())
                {
                    //too many results returned
                    project = null;
                }
            }
            return project;
        }

        protected IList<Project> BuildList(IDataReader reader)
        {
            IList<Project> projectsList = new List<Project>();
            while (reader.Read())
            {
                var project = new Project {Id = (int) reader["Id"], Name = (string) reader["Name"]};
                projectsList.Add(project);
            }
            return projectsList;
        }
    }
}